import router, { asyncRoutes, constantRoutes } from "./router";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import store from "./store";
import SSO from "@/utils/sso.js";
import { setToken, getToken } from "@/utils/auth"; // get token from cookie
import Layout from "@/layout/index";
import oldSystem from "@/views/oldSystem/iframe.vue";
import Vue from "vue";
import axios from "axios";

NProgress.configure({
  showSpinner: false,
}); // NProgress Configuration

const routes = [
  {
    path: "/home",
    component: Layout,
    meta: {
      title: "首页",
      level: 1,
      icon: require("@/assets/style/leftNav/index.png"),
      alive: true,
    },
  },
];

function fetchdata(data, rolesRouter) {
  data.forEach((item, index) => {
    let newRoute = {};
    const route = asyncRoutes.find((obj) => {
      return item.functionName === obj.meta.title;
    });
    if (route) {
      newRoute = {
        ...route,
      };
    } else {
      newRoute = {
        path: "/oldSystem" + index * 10,
        // path: '/oldSystem/',
        // name: '/oldSystem' + index,
        // component: Layout,
        redirect: "",
        meta: {
          title: item.functionName,
          level: item.functionLevel + 1,
          /* icon: require('@/assets/style/leftNav/currency.png'), */
          url: item.functionUrl || "",
        },
        /* ,
                        children: [] */
      };
      /* this.$router.addRoutes([newRoute]) */
    }
    if (item.tSFunctions && item.tSFunctions.length > 0) {
      Vue.set(newRoute, "component", Layout);
      Vue.set(newRoute, "children", []);
      item.tSFunctions.forEach((child, childIndex) => {
        const str = "0-" + index + "-" + childIndex;
        const childRoute =
          route &&
          route.children &&
          route.children.find((obj) => {
            return child.functionName === obj.meta.title;
          });
        let newChild = childRoute
          ? {
              ...childRoute,
            }
          : {};
        if (Object.keys(newChild).length === 0) {
          newChild = {
            path: "index" + index + childIndex,
            name: "index" + index + childIndex,
            component: oldSystem,
            meta: {
              title: child.functionName,
              level: child.functionLevel + 1,
              alive: true,
              url: child.functionUrl,
            },
          };
        }
        if (rolesRouter.includes(str)) {
          newRoute.children.push(newChild);
        }
        // newRoute.children.push(newChild)
      });
    } else {
      Vue.set(newRoute, "component", oldSystem);
      Vue.set(newRoute, "name", "/oldSystem" + index);
    }
    routes.push(newRoute);
  });

  router.addRoutes(routes);
  store.dispatch("menuRoute/setMenus", routes);
}

function roles(data, menu) {
  const rolesRouter = [];
  data.forEach((item) => {
    const arr = item.$ref.split("[");
    const arr1 = arr.toString().split("]");
    const rolesNum = arr1.toString().split(",");
    const str = rolesNum[1] + "-" + rolesNum[3] + "-" + rolesNum[5];
    rolesRouter.push(str);
  });
  fetchdata(menu, rolesRouter);
}

// const whiteList = ['/login', '/singleLogin', '/loginOut']
const whiteList = [];

router.addRoutes(asyncRoutes);
store.dispatch("menuRoute/setMenus", asyncRoutes);

router.beforeEach(async (to, from, next) => {
  to.query.isFetchdata = true;
  NProgress.start();
  // 检查token, 判断是否已经登录
  if (!!getToken()) {
    const token = getToken();
    if (to.name === "login") {
      next({
        path: process.env.VUE_APP_RELOGIN_REDIRECT_PATH, // 一般情况下跳转到首页
      });
    } else {
      next();
    }
  }
  // 不需要检查登录的路由写在这里
  else if (whiteList.indexOf(to.path) !== -1) {
    next();
  }
  // 跳转到单点登录页面
  else if (process.env.VUE_APP_SSO === "true") {
    console.log("-------单点登录开始-------");
    const ticket = SSO.getUrlParam("ticket");
    let service = "";
    if (process.env.VUE_APP_IS_LOCAL === "true") {
      service = `http://${window.location.host}${process.env.BASE_URL}${process.env.VUE_APP_RELOGIN_REDIRECT_PATH}`;
    } else {
      service = `${process.env.VUE_APP_RELOGIN_REDIRECT_PATH}`;
    }
    if (ticket) {
      // 走鉴权的代码
      const params = {
        ticket,
        service,
      };
      const kdpLoginUrl = `${process.env.VUE_APP_KDP_BASE_URL}/kdp/login`;
      try {
        const kdpLoginResult = await axios.post(kdpLoginUrl, params);
        if (kdpLoginResult.code === 200) {
          setToken(kdpLoginResult.data["X-Access-Token"]);
          const kdpUserUrl = `${process.env.VUE_APP_KDP_BASE_URL}/user/getUserInfo`;
          const kdpUserRes = await axios.get(kdpUserUrl);
          if (kdpUserRes.code === 200) {
            await store.setInfo(kdpUserRes.data.userInfo);
            await portfolioStore.fetchPortfolioTree(
              kdpUserRes.data.userInfo.roleIds
            );
          } else {
            Message.error("获取用户信息失败");
          }
          next();
        } else {
          SSO.redirectToSsoLoginPage(service);
        }
      } catch (error) {
        // 登录失败
        Message.error("登录失败");
      }

      // 不鉴权的代码
      // const params = {
      //   ticket,
      //   service,
      // };
      // const res: any = await axios
      //   .get(`/cas/client/validateLogin`, { params })
      //   .catch((e) => {
      //     console.error(e);
      //     SSO.redirectToSsoLoginPage(service);
      //   });
      // if (!res || res.success !== true || !res.data) {
      //   SSO.redirectToSsoLoginPage(service);
      // }
      // setToken(res.data.token); // todo 存储用户信息、token
      // await store.setInfo(res.data.userInfo);
      // await portfolioStore.fetchPortfolioTree(res.data.userInfo.roleIds); // 使用roleIds
      // next();
    } else {
      SSO.redirectToSsoLoginPage(service);
    }
    console.log("-------单点登录结束-------");
  } else {
    next();
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
